package com.xyz.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import javax.sql.DataSource;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.xyz.*")
//指定环境配置变量文件路径
@PropertySource(value = { "classpath:dbConfig.properties" })
// spring mvc 专用配置类
// 除了配置 spring框架外，还需要配置 mvc 配置项
public class AppConfig implements WebMvcConfigurer {

    // 环境参数获取用对象
    @Autowired
    private Environment env;

    // Mvc Servlet 用来配置 view 视图层的
    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        // 配置 MVC 中的 View 层
        //配置 Mvc 使用的视图代码模板
        viewResolver.setViewClass(JstlView.class);
        //视图文件路径
        viewResolver.setPrefix("/WEB-INF/views");
        //视图文件类型
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    // 配置 MVC 视图使用的静态资源
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/WEB-INF/static/css/**").addResourceLocations("/WEB-INF/static/css/");
        registry.addResourceHandler("/WEB-INF/static/image/**").addResourceLocations("/WEB-INF/static/image/");
        registry.addResourceHandler("/WEB-INF/static/js/**").addResourceLocations("/WEB-INF/static/js/");
    }

    // 配置数据源类，进行依赖注入用
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(env.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(env.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    // 依赖注入 JdbcTemplate 的 bean
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setResultsMapCaseInsensitive(true);
        return jdbcTemplate;
    }
}
